package com.lagou.edu.servlet;

import com.lagou.edu.annotation.MiniAutoWired;
import com.lagou.edu.factory.BeanFactory;
import com.lagou.edu.factory.ProxyFactory;
import com.lagou.edu.factory.impl.DefaultFactory;
import com.lagou.edu.service.ITransferService;
import com.lagou.edu.utils.JsonUtils;
import com.lagou.edu.vo.Result;
import org.dom4j.DocumentException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;

/**
 * @ClassName: TransferServlet
 * @Auther: Jerry
 * @Date: 2020/6/29 11:18
 * @Desctiption: TODO
 * @Version: 1.0
 */
@WebServlet(name = "transferServlet", urlPatterns = "/transferServlet")
public class TransferServlet extends HttpServlet {

    private ITransferService transferService;

    @Override
    public void init() {
        try {
            BeanFactory beanFactory = new DefaultFactory("beans.xml");
            transferService = (ITransferService) beanFactory.getBean("transferService");
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求参数
        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        String money = req.getParameter("money");
        Result result = new Result();
        try {

            transferService.transfer(fromCardNo, toCardNo, new BigDecimal(money));
            result.setStatus("200");
            result.setMessage("转账成功~");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.getMessage());
        }
        // 响应
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JsonUtils.object2Json(result));
    }

}
